package thread09;

public class Ticket implements Runnable{

    //100张票
    private int ticket = 100;

    private Object obj = new Object();//锁对象可以是任意类对象,这里使用的是Object类对象

/*    @Override
    public synchronized void run() {
        while (true) {
                if (ticket > 0) {
               *//* try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }*//*

                    System.out.println(Thread.currentThread().getName() + "..." + ticket);//输出一个ticket(模拟卖出去一张票),剩余的是ticket--
                    ticket = ticket - 1;
                }
            }
        }*/

    //此代码等效上边代码
/*    @Override
    public void run() {
        synchronized (this) {
            while (true) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + "..." + ticket);//输出一个ticket(模拟卖出去一张票),剩余的是ticket--
                    ticket = ticket - 1;
                }
            }
        }
    }*/

    @Override
    public void run() {
        while (true) {
            sellTicket();
        }
    }

    private synchronized void sellTicket(){
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "..." + ticket);//输出一个ticket(模拟卖出去一张票),剩余的是ticket--
            ticket = ticket - 1;
        }
    }
}